package com.litengsoft.lianmeng.controller;

import com.litengsoft.lianmeng.common.Result;
import com.litengsoft.lianmeng.common.enums.ResultCodeEnum;
import com.litengsoft.lianmeng.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;

/**
 * 微信相关服务
 */
@Slf4j
@Controller
public class WXController {

    @Resource
    private LoginService loginService;

    /**
     * 跳转登录页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/login.action")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView first = new ModelAndView("/first");
        return first;
    }

    /**
     * 获取登录二维码
     */
    @ResponseBody
    @RequestMapping("/getQRCode.action")
    public Result<String> getQRCode(HttpServletRequest request, HttpServletResponse response) {
        Result<String> result = new Result<>();
        try {
            String uuid = loginService.getWebWXUuid();
            log.info("获取uuid：{}", uuid);
            if (StringUtils.isNotBlank(uuid)) {
                String qrCode = loginService.getQRCode(uuid);
                result.build(qrCode);
                Runnable myRunnable = new Runnable() {
                    @Override
                    public void run() {
                        String redirectUrl = loginService.getLoginStatus(uuid);
                        if (StringUtils.isNotBlank(redirectUrl)) {
                            loginService.getLoginCookies(redirectUrl);
                        }
                    }
                };
                Thread thread = new Thread(myRunnable);
                thread.start();
            } else {
                log.error("登录异常，uuid获取失败");
            }
        } catch (Exception e) {
            log.error("获取登录二维码失败", e);
            result.error(ResultCodeEnum.WEB_EXCEPTION);
        }
        return result;
    }


}
